package com.yami.shop.im.hanlder;

import cn.hutool.core.util.StrUtil;
import com.yami.shop.common.util.HttpContextUtils;
import com.yami.shop.security.api.model.YamiUser;
import com.yami.shop.security.comment.exception.UnauthorizedException;
import com.yami.shop.security.comment.exception.UsernameNotFoundException;
import com.yami.shop.security.multishop.model.YamiShopUser;
import com.yami.shop.security.platform.model.YamiSysUser;
import lombok.experimental.UtilityClass;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @author LGH
 */
@Component
public class SecurityHandler {

    @Autowired
    private TokenStore tokenStore;

    /**
     * 获取用户
     */
    public YamiUser getUser(String token) {
        if (StrUtil.isBlank(token)) {
            return null;
        }
        OAuth2Authentication oAuth2Authentication = tokenStore.readAuthentication(token);
        if (oAuth2Authentication == null) {
            return null;
        }
        YamiUser details = (YamiUser) oAuth2Authentication.getUserAuthentication().getDetails();
        if (details == null) {
            return null;
        }
        return details;
    }

    /**
     * 获取用户
     */
    public YamiShopUser getShopUser(String token) {
        if (StrUtil.isBlank(token)) {
            return null;
        }
        OAuth2Authentication oAuth2Authentication = tokenStore.readAuthentication(token);
        if (oAuth2Authentication == null) {
            return null;
        }
        YamiShopUser details = (YamiShopUser) oAuth2Authentication.getUserAuthentication().getDetails();
        if (details == null) {
            return null;
        }
        return details;
    }

    /**
     * @param token 用户token
     * @return 用户信息
     */
    public YamiSysUser getSysUser(String token) {
        if (StrUtil.isBlank(token)) {
            return null;
        }
        OAuth2Authentication oAuth2Authentication = tokenStore.readAuthentication(token);
        if (oAuth2Authentication == null) {
            return null;
        }
        YamiSysUser details = (YamiSysUser) oAuth2Authentication.getUserAuthentication().getDetails();
        if (details == null) {
            return null;
        }
        return details;
    }
}
